package com.linghui.videoplus.ipai.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.VideoPlusApplication;
import com.linghui.videoplus.ipai.media.Recorder;

/**
 * 视频拍摄
 * @author chenxf
 *
 */
public class CameraActivity extends BaseActivity implements OnClickListener,OnTouchListener {
	private ImageView flushImageView;
	private Recorder recorder;
	private SurfaceView surfaceView;
	private boolean isRecording = false; 
	private boolean isFlushOn=false;
	
	private LinearLayout  homeLL;
	private LinearLayout  cameraLL;
	private LinearLayout  photoLL;
	
	private TextView timerTextView;
	private int minute = 0;
	private int second = 0;
	
	
	private Handler sensorHandler;
    private OrientationSensorListener listener;
	private SensorManager sm;
	private Sensor sensor;
	private int screenOrient=1;//右=1，上=2 左=3 下=4
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_camera);
		
//		menuLayout = (com.linghui.videoplus.ipai.view.MenuLayout) this.findViewById(R.id.menuLayout);
		homeLL =  (LinearLayout)this.findViewById(R.id.homeLL);
		cameraLL =  (LinearLayout)this.findViewById(R.id.cameraLL);
		photoLL =  (LinearLayout)this.findViewById(R.id.photoLL);
		homeLL.setOnClickListener(this);
		cameraLL.setOnClickListener(this);
		photoLL.setOnClickListener(this);
		
		sensorHandler = new ChangeOrientationHandler();
	    sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
	    sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);       
	    listener = new OrientationSensorListener(sensorHandler);
	    sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
		
		surfaceView = (SurfaceView) this.findViewById(R.id.surfaceview); 
		timerTextView=(TextView)findViewById(R.id.timerTextView);
		flushImageView=(ImageView)findViewById(R.id.flushImageView);
		flushImageView.setOnTouchListener(this);
		recorder=new Recorder(this, surfaceView);
		
	}
	
    @Override
    protected void onPause() {
    	sm.unregisterListener(listener);
    	super.onPause();
    }
    
    @Override
    protected void onResume() {
    	sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
    	super.onResume();
    }

	@Override
	public void onClick(View v) {
		
		if(v==photoLL){
			if(isRecording){
				doCancelCamera(REQUEST_CODE_VIDEO_CASCADE);	
			}else{
				VideoCascadeActivity.launch(CameraActivity.this, REQUEST_CODE_DEFAULT,REQUEST_CODE_VIDEO_CASCADE);
			}
		
		}else if(v==cameraLL){
			cameraLL.setEnabled(false);
			doCamera();
			new Handler().postDelayed(new Runnable(){

				@Override
				public void run() {
					cameraLL.setEnabled(true);
				}
				
			},2000);
			
		}else if(v==homeLL){
			if(isRecording){
				doCancelCamera(REQUEST_CODE_DEFAULT);	
			}else{
				BrowserActivity.launch(CameraActivity.this,VideoPlusApplication.getUrlIndex(this), REQUEST_CODE_CAMERA, REQUEST_CODE_DEFAULT);
			}
		}
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(v==flushImageView){
			if(event.getAction()==MotionEvent.ACTION_UP){
				if(!isFlushOn){
					recorder.onFlush();
					flushImageView.setImageResource(R.drawable.flash_off_up);
					isFlushOn=true;
				}else if(isFlushOn){
					recorder.offFlush();
					flushImageView.setImageResource(R.drawable.flash_on_up);
					isFlushOn=false;
				}
			}	
			return true;
		}
		return false;
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK || keyCode==KeyEvent.KEYCODE_HOME){
			if(isRecording){
				doCancelCamera(REQUEST_CODE_DEFAULT);	
			}else{
				BrowserActivity.launch(this, VideoPlusApplication.getUrlIndex(this),REQUEST_CODE_CAMERA, REQUEST_CODE_DEFAULT);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 拍摄
	 */
	public void doCamera(){
		if(!isRecording){
			recorder.record(screenOrient);
			showToast("开始录制!");
			isRecording=true;
			timerTextView.setVisibility(View.VISIBLE);
			flushImageView.setVisibility(View.GONE);
			handler.postDelayed(task, 1000);
		}else{
			recorder.stop();
			isRecording=false;
			timerTextView.setText( format(minute) + ":"+ format(second));
		}
		
		
	}
	
	/**
	 * 取消拍摄
	 */
	public void doCancelCamera(final int toCode){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("您将会丢失正在拍摄的视频,是否取消拍摄?");
		builder.setCancelable(false);
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				recorder.cancle();
				isRecording=false;
				timerTextView.setVisibility(View.GONE);
				if(toCode==REQUEST_CODE_VIDEO_CASCADE){
					VideoCascadeActivity.launch(CameraActivity.this, REQUEST_CODE_DEFAULT,REQUEST_CODE_VIDEO_CASCADE);
				}else if(toCode==REQUEST_CODE_DEFAULT){
					BrowserActivity.launch(CameraActivity.this,VideoPlusApplication.getUrlIndex(CameraActivity.this), REQUEST_CODE_CAMERA, REQUEST_CODE_DEFAULT);
				}
			}
		});
		builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
		
	}
	
	
	/*
	 * 定时器设置，实现计时
	 */
	private Handler handler = new Handler();
	private Runnable task = new Runnable() {
		public void run() {
			if (isRecording) {
				handler.postDelayed(this, 1000);
				second++;
				if (second >= 60) {
					recorder.stop();
					isRecording=false;
					minute++;
					second = second % 60;
				}
				timerTextView.setText( format(minute) + ":"+ format(second));
			}
		}
	};
	/*
	 * 格式化时间
	 */
	public String format(int i) {
		String s = i + "";
		if (s.length() == 1) {
			s = "0" + s;
		}
		return s;
	}
	
	public static void launch(Activity mActivity,int fromCode,int toCode) {
		Intent intent = new Intent(mActivity, CameraActivity.class);
		intent.putExtra(FROM_CODE_KEY, fromCode);
		intent.putExtra(TO_CODE_KEY, toCode);
		mActivity.startActivity(intent);
		mActivity.finish();
	}
	
	
	class OrientationSensorListener implements SensorEventListener {
		 private static final int _DATA_X = 0;
	     private static final int _DATA_Y = 1;
	     private static final int _DATA_Z = 2;
	     public static final int ORIENTATION_UNKNOWN = -1;
	     private Handler rotateHandler;
		public OrientationSensorListener(Handler handler) {
			rotateHandler = handler;
		}

		public void onAccuracyChanged(Sensor arg0, int arg1) {
		}

		public void onSensorChanged(SensorEvent event) {
			float[] values = event.values;
	        int orientation = ORIENTATION_UNKNOWN;
	        float X = -values[_DATA_X];
	        float Y = -values[_DATA_Y];
	        float Z = -values[_DATA_Z];        
	        float magnitude = X*X + Y*Y;
	        // Don't trust the angle if the magnitude is small compared to the y value
	        if (magnitude * 4 >= Z*Z) {
	            float OneEightyOverPi = 57.29577957855f;
	            float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
	            orientation = 90 - (int)Math.round(angle);
	            // normalize to 0 - 359 range
	            while (orientation >= 360) {
	                orientation -= 360;
	            } 
	            while (orientation < 0) {
	                orientation += 360;
	            }
	        }
	        
	        if (rotateHandler!=null) {
				rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
			}
		}
	};
	class ChangeOrientationHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {  
			if (msg.what==888) {
				int orientation = msg.arg1;
				if (orientation>45&&orientation<135) {//头朝右	
					Log.i("test", "111");		
					screenOrient=1;
				}else if (orientation>135&&orientation<225){//头朝下
					Log.i("test", "444");
					screenOrient=4;
				}else if (orientation>225&&orientation<315){//头朝左
					Log.i("test", "333");
					screenOrient=3;
				}else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){//头朝上
					Log.i("test", "222");
					screenOrient=2;
				}
			}
			super.handleMessage(msg);        		
		}
	};

}
